package com.financing.controller.user;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

import com.financing.common.CONST;
import com.financing.components.payment.Gateway;
import com.financing.components.sms.Sms;
import com.financing.enums.invest.CouponRule;
import com.financing.enums.invest.InvestLogType;
import com.financing.enums.notify.AgentNotify;
import com.financing.enums.notify.AssetsNotify;
import com.financing.enums.notify.SmsNotify;
import com.financing.model.Data;
import com.financing.model.invest.Deposit;
import com.financing.model.user.User;
import com.financing.service.invest.CouponService;
import com.financing.service.invest.InvestLogService;
import com.financing.service.system.AssetsLogService;
import com.financing.service.system.LoggerService;
import com.financing.service.user.DepositService;
import com.financing.util.DateUtil;
import com.financing.util.Json;
import com.financing.util.Money;
import com.financing.util.Str;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

/**
 * 充值控制器
 * @author 无处不在的二叔
 */
public class DepositController extends Controller {
	private LoggerService log = new LoggerService();
	private DepositService deposit = new DepositService();	
	private CouponService conpon = new CouponService();	
	private AssetsLogService assetsLog = new AssetsLogService();	
	private static final Logger logger = Logger.getLogger(UserController.class);
	
	/**
	 * 充值
	 * @throws Exception 
	 */
	public void index1() throws Exception {
		User u = getAttr("user");
		double amount = Double.valueOf(getPara("amount")); 
		String type = getPara("type","app"); 
		String mode = getPara("mode","quick"); 
		String service = "";
		if(Str.eq("app", type)) {
			service = Str.eq("quick", mode) ? "/app/500002" : "/app/500001";
		}else if(Str.eq("web", type)) {
			service = Str.eq("quick", mode) ? "/500405" : "/500002";
		}				
		if(amount>=100) {
			// 检查用户是否已绑卡
			if(u.getIsBindBankCard()==1){
				// Gateway.托管充值
				String code = DateUtil.getTimeStamp();
				// String summary = "用户="+u.get("mobile")+" 充值金额="+amount+" 手续费="+CONST.find("DEPOSIT_USER_FEE");
				Map<Object, Object> data = Gateway.form(service, Data.put(
					"mchnt_txn_ssn",code,
					"login_id",u.getCode(),
					"amt",Double.valueOf(amount*100).intValue(),
					"page_notify_url",CONST.URL+"/app/page/user-return", 
					"back_notify_url",CONST.URL+"/deposit/toNotify",
					"sign","amt,back_notify_url,login_id,mchnt_cd,mchnt_txn_ssn,page_notify_url"
				));
				
				// 新建充值记录
				Deposit d = new Deposit();
				d.setUserId(u.getId());
				d.setCode(code);
				d.setCreateTime(new Date());
				d.setAmount(amount);
				d.setUserFee(Double.valueOf(CONST.find("DEPOSIT_USER_FEE")));
				d.setPlatFee(Double.valueOf(CONST.find("DEPOSIT_PLAT_FEE")));
				d.setMobile(u.getMobile());
				d.setRealName(u.getRealName());
				d.setSummary("充值金额"+amount+"元");
				d.setStatus("process"); 
				d.save();
				
				setAttr("data", data);
				render("/view/app/user/deposit.html");
			}else{
				renderJson(Json.error("用户未实名绑卡！"));
			}
		}else{
			renderJson(Json.error("充值金额不可小于100元！"));
		}
	}	

	/**
	 * 充值异步回调
	 */
	@Clear
	public void toNotify() throws Exception {
		String code = getPara("mchnt_txn_ssn","");
		String date = DateUtil.format(DateUtil.DATE_LOCAL_FORMAT);
		String status = getPara("resp_code","");
		String message = getPara("resp_desc","");
		Deposit d = deposit.findByCode(code);
		User u = User.me.findById(d.getUserId());
		
		if(Str.nb(code) && Str.eq("process", d.getStatus()) && u!=null){
			if(Str.eq("0000", status)){
				String depositAmount = getPara("amt");
				
				// 修改充值记录状态 & 实际到帐金额
				d.setStatus("success").update();
	
				// 插入充值交易记录
				InvestLogService.build("充值", InvestLogType.DEPOSIT, d.getId(), d.getAmount(), d.getUserId(), "success", "充值实际到帐"+Money.div(Double.valueOf(depositAmount), 100)+"元", code);

				// 获取充值奖励
				conpon.available(d.getUserId(), CouponRule.DEPOSIT, d.getAmount());
				
				// 发送充值成功消息
				AssetsNotify notify = AssetsNotify.DESPOSIT_SUCCESS;
				AgentNotify agentNotify = AgentNotify.DESPOSIT_SUCCESS;
				assetsLog.bulid(u, notify.getName(), Str.format(notify.getContents(), date, d.getAmount()),Str.format(agentNotify.getContents(), u.getMobile()+"（"+u.getRealName()+"）", date, d.getAmount(), u.getAvailableAmount()));
				
				// 发送充值成功短信提醒
				Sms.send(u.getMobile(), Str.format(SmsNotify.DESPOSIT_SUCCESS, date, d.getAmount()));
	
				// 日志记录
				log.build("充值", "用户成功充值"+d.getAmount()+"元", u.getId(), "user");
			}else{					
				// 更新状态
				d.setStatus("failed").setSummary(message).update();

				// 插入充值交易记录
				InvestLogService.build("充值", InvestLogType.DEPOSIT, d.getId(), d.getAmount(), d.getUserId(), "failed", message, code);
				
				// 发送充值失败消息
				AssetsNotify notify = AssetsNotify.DESPOSIT_FAILED;
				AgentNotify agentNotify = AgentNotify.DESPOSIT_FAILED;
				assetsLog.bulid(u, notify.getName(), Str.format(notify.getContents(), date, d.getAmount(), CONST.find("PLAT_PHONE")), Str.format(agentNotify.getContents(), u.getMobile()+"（"+u.getRealName()+"）", date, u.getAvailableAmount()));
				
				// 日志记录
				log.build("充值", "用户充值失败，原因："+message, u.getId(), "user");
			}
		}else{
			logger.error(code+"数据不存在");
		}
		renderHtml(Gateway.response(code));
	}
	
	/**
	 * 充值列表
	 */
	public void list() { 
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String,String> params = Data.flat(getParaMap());
		Page<Deposit> p = deposit.list(page,size,params);
		for(Deposit d : p.getList()) {
			d.put("user", User.me.findById(d.getUserId()));
		}
		
		// 计算总充值金额
		params.put("status", "success");
		double total = deposit.sumByParams(params);
		
		// 计算总充值笔数
		double success_count = deposit.countByParams(params);
		params.remove("status");
		double total_count= deposit.countByParams(params);
		
		renderJson(Json.ok("数据获取成功！", Data.put("total_count",total_count,"success_count",success_count,"total",total,"page",p)));
	}
}
 